<template>
  <div class="personal-information-user-page">
   <el-form-item>
     <div class="form-buttons">
       <el-button @click="$router.go(-1)">返回</el-button>
       <el-button type="primary" @click="handleSubmit">修改</el-button>
     </div>
   </el-form-item>
 
   <el-row justify="center" align="middle" style="height: 10vh;">
     <el-col :span="10">
       <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="personal-info-form">
         <!-- ID 和 真实姓名 -->
         <el-row>
           <el-col :span="12">        
             <el-form-item label="ID" prop="id">
               <el-input v-model="form.id" placeholder="123" :disabled="true" />
             </el-form-item>
           </el-col>
           <el-col :span="12">    
             <el-form-item label="真实姓名" prop="realName">
               <el-input v-model="form.realName" placeholder="小明" :disabled="true" />
             </el-form-item>
           </el-col>
         </el-row>
         
         <!-- 用户角色 和 用户名称 -->
         <el-row>
           <el-col :span="12">
             <el-form-item label="用户角色" prop="role">
               <el-input v-model="form.role" placeholder="用户" :disabled="true" />
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="用户名称" prop="username">
               <el-input v-model="form.username" placeholder="请输入用户名" :disabled="true" />
             </el-form-item>
           </el-col>
         </el-row>
 
         <!-- 出生日期 和 性别 -->
         <el-row>
           <el-col :span="12">
             <el-form-item label="出生日期" prop="birthDate">
               <el-date-picker
                 v-model="form.birthDate"
                 type="date"
                 placeholder="选择日期"
                 format="YYYY-MM-DD"
                 value-format="YYYY-MM-DD"
               />
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="性别" prop="gender">
               <el-radio-group v-model="form.gender">
                 <el-radio :label="0">男</el-radio>
                 <el-radio :label="1">女</el-radio>
               </el-radio-group>
             </el-form-item>
           </el-col>
         </el-row>
 
         <!-- 邮箱 和 密码 -->
         <el-row>
           <el-col :span="12">
             <el-form-item label="邮箱" prop="email">
               <el-input v-model="form.email" placeholder="请输入邮箱" />
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="修改密码" prop="password">
               <el-input v-model="form.password" type="password" placeholder="请输入新密码" show-password />
             </el-form-item>
           </el-col>
         </el-row>
 
         <!-- 确认密码 -->
         <el-row>
           <el-col :span="12">
             <el-form-item label="确认密码" prop="repassword">
               <el-input v-model="form.repassword" type="password" placeholder="请确认密码" show-password />
             </el-form-item>
           </el-col>
         </el-row>
 
         <!-- 头像上传 -->
         <el-form-item label="头像" prop="avatar">
           <el-upload
             class="avatar-uploader"
             :show-file-list="true"
             :before-remove="beforeRemove"
             :before-upload="beforeAvatarUpload"
             :on-remove="handleRemove"
             name="file"
           >
             <img v-if="imageUrl" :src="imageUrl" class="avatar" />
             <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
           </el-upload>
         </el-form-item>
       </el-form>
     </el-col>
   </el-row>
   </div>
 </template>
 
 <script setup>
 import { ref, onMounted } from 'vue';
 import { useLoginStore } from "@/store/login";
 import { searchUser, updateUserInfo } from "@/api";
 import { ElMessage } from 'element-plus';
 import { Plus } from '@element-plus/icons-vue';
 import { dayjs } from 'element-plus';
 import { fileToBase64 } from '@/utils/FileToBase64.js';
 import { useHeaderStore } from '@/store/header';
 import { storeToRefs } from 'pinia'
 
 const loginStore = useLoginStore();
 const headerStore = useHeaderStore()
 const { userName,userImg } = storeToRefs(headerStore)
 const formRef = ref(null);
 const imageUrl = ref('');
 
 const form = ref({
   id: '',
   realName: '',
   role: '',
   username: '',
   birthDate: '',
   gender: 0,
   email: '',
   password: '',
   repassword: '',
   avatar: '',
   file: ''
 });
 
 // 表单验证规则
 const rules = {
   username: [
     { required: true, message: '请输入用户名', trigger: 'blur' },
     { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
   ],
   email: [
     { required: true, message: '请输入邮箱地址', trigger: 'blur' },
     { type: 'email', message: '请输入正确的邮箱地址', trigger: 'change' },
     { min: 5, max: 20, message: '邮箱长度在 5 到 20 个字符', trigger: 'blur' }
   ],
   birthDate: [
     { required: true, message: '请选择出生日期', trigger: 'change' }
   ],
   gender: [
     { type: 'number', required: true, message: '请选择性别', trigger: 'blur' }
   ],
   password: [
     { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
   ],
   repassword: [
     { validator: (rule, value, callback) => {
       if (form.value.password && !value) {
         callback(new Error('请确认密码'));
       } else if (value !== form.value.password) {
         callback(new Error('两次输入密码不一致'));
       } else if (value && (value.length < 6 || value.length > 20)) {
         callback(new Error('密码长度在 6 到 20 个字符'));
       } else {
         callback();
       }
     }, trigger: 'blur' }
   ]
 };
 
 // 获取个人信息
 const getUserInfo = async () => {
   try {
     const userId = loginStore.userInfo.data.userId;
     const res = await searchUser({ userId });
     
     if (res.data.code === 200) {
       const userInfo = res.data.data;
       loginStore.setUserInfo(res.data);
       res.data.msg = "登录成功";
       localStorage.setItem('userInfo', JSON.stringify(res.data));
       form.value = {
         id: userInfo.userId || '',
         realName: userInfo.name || '',
         role: userInfo.roleId === '1' ? '管理员' : '普通用户',
         username: userInfo.username || '',
         birthDate: dayjs(userInfo.birthday*1).format('YYYY-MM-DD') || '',
         gender: userInfo.gender !== undefined ? Number(userInfo.gender) : 0,
         email: userInfo.email || '',
         password: '',
         repassword: '',
         avatar: userInfo.avatar || '',
         file: ''
       };
       
       if (userInfo.avatar) {
         imageUrl.value = userInfo.avatar;
       }
     }
   } catch (error) {
     console.error('获取用户信息错误:', error);
     ElMessage.error('获取用户信息失败');
   }
 };
 
 // 修改头像上传相关的方法
 const beforeAvatarUpload = (file) => {
     // 验证文件类型和大小
     const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
     const isLt2M = file.size / 1024 / 1024 < 2;
 
     if (!isJPG) {
         ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
         return false;
     }
     if (!isLt2M) {
         ElMessage.error('上传头像图片大小不能超过 2MB!');
         return false;
     }
 
     // 添加预览
     imageUrl.value = URL.createObjectURL(file);
     form.value.file = file;
     return true;
 };
 
 // 移除文件的处理
 const beforeRemove = (file) => {
     form.value.file = '';
     return true;
 };
 
 // 添加删除方法
 const handleRemove = (file) => {
   ElMessageBox.confirm(
     '确定要删除这张图片吗？',
     '提示',
     {
       confirmButtonText: '确定',
       cancelButtonText: '取消',
       type: 'warning',
     }
   )
     .then(() => {
       form.value.file = '';
       imageUrl.value = ''; // 清除预览图片
       ElMessage.success('删除成功');
     })
     .catch(() => {
       // 取消删除
     });
 };
 
 // 修改提交方法
 const handleSubmit = async () => {
   try {
     await formRef.value.validate();
     
     // 转换生日为时间戳
     const birthday = form.value.birthDate ? new Date(form.value.birthDate).getTime() : null;
     console.log('生日时间戳:', birthday); // 调试用
     
     const submitData = new FormData();
     
     // 添加基本信息
     submitData.append('userId', form.value.id);
     submitData.append('name', form.value.realName);
     submitData.append('roleId', form.value.role === '管理员' ? '1' : '0');
     submitData.append('username', form.value.username);
     submitData.append('gender', form.value.gender);
     submitData.append('email', form.value.email);
     
     // 添加生日
     if (birthday) {
       submitData.append('birthday', birthday);
     }
     
     // 添加密码（如果有）
     if (form.value.password) {
       submitData.append('password', form.value.password);
       submitData.append('repassword', form.value.repassword);
     }
     
     // 添加文件（如果有）
     if (form.value.file) {
       submitData.append('file', form.value.file);
     }

     // 打印提交的数据（调试用）
     for (let pair of submitData.entries()) {
       console.log(pair[0] + ': ' + pair[1]);
     }
     
     const res = await updateUserInfo(submitData);
     
     if (res.data.code === 200) {
       ElMessage.success('个人信息更新成功');
       userName.value = form.value.realName;
       if (form.value.file) {
         fileToBase64(form.value.file).then(res => {
           userImg.value = res; //转换为base64
         });
       }
       getUserInfo();
     } else {
       ElMessage.error(res.data.message || '更新失败');
     }
   } catch (error) {
     console.error('提交表单错误:', error);
     ElMessage.error('提交失败，请检查表单信息');
   }
 };
 
 onMounted(() => {
   getUserInfo();
 });
 </script>
 
 <style scoped>
 .form-buttons {
   width: 100%;
   display: flex;
   justify-content: flex-end;
   align-items: center;
  padding: 50px;
 }
 
 .personal-info-form {
   width: 100%;
   max-width: 600px;
   margin: 0 auto;
   position: relative;
 }
 
 .avatar {
   width: 100px;
   height: 100px;
   border-radius: 50%;
   object-fit: cover;
   margin-top: 10px;
 }
 
 .avatar-uploader {
   display: inline-block;
 }
 
 .avatar-uploader .el-upload {
   border: 2px solid #b3b3b3;
   border-radius: 8px;
   cursor: pointer;
   position: relative;
   overflow: hidden;
   transition: all 0.3s ease;
 }
 
 .el-icon.avatar-uploader-icon {
   font-size: 40px;
   border: 2px solid #ccc;
   color: #8c939d;
   width: 150px;
   height: 150px;
   text-align: center;
   line-height: 100px;
 }
 
 .p {
   color: #ccc;
   padding-left: 100px;
 }
 
 .personal-information-user-page{
   width: 100%;
   height: 100%;
 }
 
 </style>
 
 